<template>
  <div>
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
        <el-form-item label="平台名称" prop="name">
          <el-input v-model="queryParams.name" clearable placeholder="请输入平台名称" />
        </el-form-item>
        <el-form-item label="平台代码" prop="code">
          <el-input v-model="queryParams.code" clearable placeholder="请输入平台代码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSearch()">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <div class="tips-content">
        <el-dropdown style="margin-right: 10px" @command="handleClickBatch($event, 'Rows', {})">
          <el-button type="primary" style="margin-bottom: 10px">
            批量操作
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="close">禁用</el-dropdown-item>
              <el-dropdown-item command="open">启用</el-dropdown-item>
              <el-dropdown-item command="reload">刷新平台余额</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <!-- <el-button
          type="primary"
          :disabled="!current.remark"
          style="margin-right: 0px; margin-bottom: 10px"
          @click="handleCancel"
        >
          取消当前平台
        </el-button> -->
        <el-button
          type="primary"
          style="margin-right: 10px; margin-bottom: 10px"
          @click="realodBalance(false)"
        >
          刷新全部余额
        </el-button>
        <!-- <div class="alert-contnet">当前接码平台：{{ current.remark || "--" }}</div> -->
        <!-- <el-alert style="margin-bottom: 10px;" :title="`当前接码平台：${current.remark || '--'}`" type="success" :closable="false" /> -->
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        :preserve-expanded-content="preserveExpanded"
        :row-key="(e) => e.row.id"
        :expand-row-keys="expandRowKeys"
        @selection-change="handleSelectionChange"
        @expand-change="handleChangeExpand"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column type="expand" fixed="left">
          <template #default="{ row }">
            <div m="4" style="display: flex; flex-wrap: wrap">
              <div
                v-for="(item, index) in row.row.config"
                :key="index"
                style="margin: 5px"
                class="flex"
              >
                <el-tag type="success">{{ index }}</el-tag>
                ：
                <el-popover
                  v-if="item.length > 50"
                  class="box-item"
                  width="500"
                  :content="item"
                  placement="top"
                >
                  <template #reference>
                    <div class="single-line-ellipsis valueContent">{{ item }}</div>
                  </template>
                </el-popover>
                <div v-else class="valueContent">{{ item }}</div>
              </div>
            </div>
            <div m="4">
              <div style="margin-bottom: 10px">
                <div v-html="row.row._number"></div>
                <div v-html="row.row._code"></div>
                <div v-html="row.row._free"></div>
              </div>
              <el-button type="primary" size="small" @click="handleTest('number', row.row)">
                测试取号
              </el-button>
              <el-button type="primary" size="small" @click="handleTest('code', row.row)">
                测试取码
              </el-button>
              <el-button type="primary" size="small" @click="handleTest('free', row.row)">
                测试释放
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="ID" prop="id" min-width="50">
          <template #default="scope">
            {{ scope.row.row.id || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="remark" min-width="160" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.row.remark || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="平台名称" prop="name" min-width="160">
          <template #default="scope">
            <div v-if="scope.row.name == scope.row.code">
              {{ scope.row.row.name || "--" }}
            </div>
            <div v-else>{{ scope.row.row.name || "--" }}（{{ scope.row.row.code }}）</div>
          </template>
        </el-table-column>

        <el-table-column label="国家" prop="countryCode" min-width="160" align="center">
          <template #default="scope">
            <span
              v-if="scope.row.row.countryCode"
              class="flag-icon"
              :class="`flag-icon-${
                scope.row.row.countryCode.length > 2
                  ? getCountriesListIcon(scope.row.row.countryCode)?.toLowerCase()
                  : scope.row.row.countryCode.toLowerCase()
              }`"
            ></span>
            <!-- {{
              getCountryName(
                scope.row.row.countryCode.length > 2
                  ? getCountriesListIcon(scope.row.row.countryCode)?.toLowerCase()
                  : scope.row.row.countryCode.toLowerCase()
              ) || "--"
            }} -->
            {{ getCountryName(scope.row.row.countryCode) || "--" }}
            {{
              scope.row.row.countryCode
                ? `（${
                    scope.row.row.countryCode.length > 2
                      ? getCountriesListIcon(scope.row.row.countryCode)
                      : scope.row.row.countryCode
                  }）`
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="产品" prop="app" min-width="90" align="center">
          <template #default="scope">
            {{ scope.row.row.app || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="switcher" min-width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.row.switcher === 'closed'" type="danger">禁用</el-tag>
            <el-tag v-else type="success">启用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="" prop="stat" width="400" align="center">
          <template #header>
            <div>
              <div>统计</div>
              <div style="font-size: 10px !important; font-weight: 400">
                （号码总数 / 收到验证码数 / 成功数 / 成功率）
              </div>
            </div>
          </template>
          <template #default="scope">
            <div style="position: relative">
              {{
                typeof scope.row.stat.totalNumbers === "number" ? scope.row.stat.totalNumbers : "--"
              }}
              /
              {{
                typeof scope.row.stat.codeReceivedNumbers === "number"
                  ? scope.row.stat.codeReceivedNumbers
                  : "--"
              }}
              /
              {{
                typeof scope.row.stat.successNumbers === "number"
                  ? scope.row.stat.successNumbers
                  : "--"
              }}
              /
              {{
                typeof scope.row.stat.successRate === "number"
                  ? scope.row.stat.successRate + "%"
                  : "--"
              }}
              <el-button
                style="position: absolute; top: 0; right: 10px"
                type="primary"
                text
                size="small"
                @click="openStatistics(scope.row.byCountry)"
              >
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="余额" prop="app" min-width="90" align="center">
          <template #default="scope">
            {{ scope.row.row.balance || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="刷新时间" prop="createdAt" min-width="160" align="center">
          <template #default="scope">
            {{ scope.row.row.updatedAt ? formatDate(scope.row.row.createdAt) : "--" }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="刷新时间" prop="updatedAt" min-width="160" align="center">
          <template #default="scope">
            {{ scope.row.row.updatedAt ? formatDate(scope.row.row.updatedAt) : "--" }}
          </template>
        </el-table-column> -->
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-dropdown @command="handleCommand($event, scope.row.row)">
              <span class="el-dropdown-link">
                操作
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.row.switcher == 'closed'"
                    command="handleSwitcherOpen"
                  >
                    启用
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.row.switcher == 'opened'"
                    command="handleSwitcherClose"
                  >
                    禁用
                  </el-dropdown-item>
                  <el-dropdown-item command="setCurrent">设为当前平台</el-dropdown-item>
                  <el-dropdown-item command="reload">刷新平台余额</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- <el-button type="text" @click="handleDel(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="paging.page"
          v-model:page-size="paging.size"
          :page-sizes="['10', '20', '30', '50', '100']"
          :size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <Form ref="formRef" @refresh="getList" />
      <Testform ref="testFormRef" @callback="getTestResult" />
      <ApiForm ref="apiFormRef" @refresh="getList" />
      <Statistics ref="statisticsRef" />
    </el-card>
  </div>
</template>

<script setup>
// import { View } from "@element-plus/icons-vue";
import Statistics from "./statistics.vue";
import ApiForm from "./apiForm.vue";
import Testform from "./testForm.vue";
import Form from "./form.vue";
import useToggle from "@/hooks/useToggle";
import { formatDate } from "@/utils";
import {
  configList,
  delConfig,
  getFormOptions,
  setCurrentApi,
  configSwitch,
  queryBalance,
} from "@/api/platformConfig/index.api";
import useCountries from "@/hooks/useCountries";
import { ElMessage, ElMessageBox } from "element-plus";

const { getCountryName, getCountriesListIcon } = useCountries();
const [loading, _, setLoading] = useToggle();

// console.log(countriesListIcon);
// let countriesListIconFn = ref(countriesListIcon);

const statisticsRef = ref(null);
const openStatistics = (data) => {
  statisticsRef.value.init(data);
};

const realodBalance = async (cfgIds) => {
  if (cfgIds) {
    queryBalance({ cfgIds }).finally(() => {
      ElMessage.success("刷新成功");
      getList();
    });
  } else {
    queryBalance().finally(() => {
      ElMessage.success("刷新成功");
      getList();
    });
  }
};

const handleStatusSwitch = (ids, status) => {
  const tips = status == "open" ? "确定要启用吗？" : "确定要禁用吗？";

  ElMessageBox.confirm(tips, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    configSwitch({
      ids,
      switcher: status,
    }).then(() => {
      ElMessage.success("操作成功");
      handleQuery();
    });
  });
};

const preserveExpanded = ref(true);

const queryParams = ref({
  name: void undefined,
  code: void undefined,
});

const paging = ref({
  page: 1,
  size: 10,
  total: 0,
});

const tableData = ref([]);
const formRef = ref(null);
const apiFormRef = ref(null);
const handleCommand = (e, row) => {
  console.log(row, e);

  if (e === "delete") {
    handleDel(row);
  } else if (e === "edit") {
    getFormOptions({ code: row.code }).then((res) => {
      if (row.code == "api")
        return apiFormRef.value.handleOpen(
          res,
          row.id,
          { ...row.config, remark: row.remark },
          row.thirdId
        );
      formRef.value.handleOpen(
        res,
        row.thirdId,
        { ...row.config, remark: row.remark },
        row.id,
        row.code
      );
    });
  } else if (e === "setCurrent") {
    setCurrent(row);
  } else if (e === "handleSwitcherOpen") {
    handleStatusSwitch([row.id], "open");
  } else if (e === "handleSwitcherClose") {
    handleStatusSwitch([row.id], "close");
  } else if (e === "reload") {
    realodBalance([row.id]);
  }
};

// const handleCancel = () => {
//   ElMessageBox.confirm("确定取消当前接码平台？", "温馨提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   }).then(() => {
//     setCurrentApi({ smsId: 0 }).then(() => {
//       handleQuery();
//       ElMessage({
//         message: "取消成功",
//         type: "success",
//       });
//     });
//   });
// };

const setCurrent = (row) => {
  ElMessageBox.confirm("确定设为当前平台？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    setCurrentApi({ smsId: row.id }).then(() => {
      handleQuery();
      ElMessage({
        message: "设置成功",
        type: "success",
      });
    });
  });
};

let thisRow = null;
const testFormRef = ref(null);
const handleTest = (type, row) => {
  thisRow = row;
  testFormRef.value.handleOpen({ type, id: row.id, app: row.app });
};

const expandRowKeys = ref([]);
const handleChangeExpand = (e) => {
  if (expandRowKeys.value.includes(e.row.row.id)) {
    expandRowKeys.value = expandRowKeys.value.filter((id) => id !== e.row.row.id);
    return;
  }
  expandRowKeys.value.push(e.row.row.id);
  console.log(expandRowKeys, "expandRowKeys");
};

const formatJson = (obj) => {
  let json = JSON.stringify(obj);
  json = json.replace(/,/g, ",<br >&nbsp;&nbsp;&nbsp;&nbsp;");
  json = json.replace(/{/g, "{<br >&nbsp;&nbsp;&nbsp;&nbsp;");
  json = json.replace(/}/g, "&nbsp;&nbsp;&nbsp;&nbsp;<br >}");
  return json;
};

const getTestResult = (e) => {
  console.log(e, "结果");
  thisRow["_" + e.type] = formatJson(e.res);
};

const handleDel = (row) => {
  ElMessageBox.confirm("确定删除该数据？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delConfig({ ids: [row.id] }).then(() => {
      handleQuery();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });
  });
};

const handleSizeChange = (e) => {
  paging.value.size = e;
  getList();
};
const handleCurrentChange = (e) => {
  paging.value.page = e;
  getList();
};

const ids = ref([]);
const handleSelectionChange = (e) => {
  ids.value = e.map((item) => item.row.id);
};

const current = ref({});
const getList = async () => {
  try {
    setLoading(true);
    const res = await configList({
      page: paging.value.page,
      size: paging.value.size,
      name: queryParams.value.name || void undefined,
      code: queryParams.value.code || void undefined,
    }).finally(() => {
      setLoading(false);
    });
    setLoading(false);

    paging.value.total = res.count;
    tableData.value = res.rows;

    const currentLine = res.rows.find((item) => item.row.id === res.current);
    current.value = currentLine.row || "--";
  } finally {
    setLoading(false);
  }
};

const handleQuery = () => {
  paging.value.page = 1;
  paging.value.size = 10;
  getList();
};

const handleSearch = () => {
  paging.value.page = 1;
  getList();
};

handleQuery();

const queryFormRef = ref(null);
const handleResetQuery = () => {
  if (!queryFormRef.value) return;
  queryFormRef.value.resetFields();
  handleSearch();
};

const handleClickBatch = (command) => {
  const commands = {
    open: () => {
      handleStatusSwitch(ids.value, "open");
    },
    close: () => {
      handleStatusSwitch(ids.value, "close");
    },
    reload: () => {
      realodBalance(ids.value);
    },
  }[`${command}`];

  return commands && commands();
};

// const handleDelete = (row) => {
//   if (!row.row.id && ids.value.length === 0) return ElMessage.warning("请选择要删除的记录");
//   const tips = `确定删除${!row.row.id ? `${ids.value.length}条记录` : "这条记录"}?`;

//   ElMessageBox.confirm(tips, "温馨提示", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   }).then(() => {
//     del();
//   });

//   const del = async () => {
//     if (row.id) {
//       // eslint-disable-next-line no-undef
//       const res = await delIds({ ids: [Number(row.id)] });
//       console.log(res);
//       if (res) {
//         ElMessage.success("删除成功");
//         handleQuery();
//       }
//       return;
//     }

//     // eslint-disable-next-line no-undef
//     const res = await delIds({ ids: ids.value });
//     if (res) {
//       ElMessage.success("删除成功");
//       handleQuery();
//     }
//   };
// };

// const handleAddRow = (row) => {
//   console.log(row);
//   formRef.value.handleOpen(row);
// };
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
.tips-content {
  display: flex;
  align-items: center;
  .alert-contnet {
    width: 100%;
    height: 40px;
    padding-left: 10px;
    margin-bottom: 10px;
    margin-left: 10px;
    line-height: 40px;
    color: #67c23a;
    background-color: #67c23a30;
    border-radius: 4px;
  }
}

.valueContent {
  max-width: 500px; /* 或者指定具体宽度 */
  padding: 5px;
  font-size: 11px;
  font-weight: 400;
  color: #67c23a;
  background-color: rgb(209.4, 236.7, 195.9, 0.4);
  border-radius: 5px;
}
.single-line-ellipsis {
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  word-break: break-all;
  white-space: nowrap; /* 禁止换行 */
}
</style>
